package com.fsp.blog.admin.service;

import com.fsp.blog.admin.pojo.Admin;
import com.fsp.blog.admin.pojo.Permission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author fushengping
 * @className AuthService
 * @description 授权认证
 * @date 2021/11/24 22:05
 */
@Component
public class AuthService {
    @Autowired
    private AdminService adminService;

    public Boolean auth(HttpServletRequest request, Authentication authentication) {
        //权限认证
        /*
        * 1.通过HttpServletRequest获得请求路径（该角色的对应权限中也有路径）
        * 2.通过authentication获取授权用户信息
        * 3.用授权信息的name来查询用户id,从而连表查询出该用户有哪些授权资源路径
        * */
        String requestURI = request.getRequestURI();
        Object principal = authentication.getPrincipal();//授权信息
        //true代表放行 false 代表拦截
        if (principal == null || "anonymousUser".equals(principal)) {
            return false;
        }
        //security的授权对象获得用户名
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        //查询该用户拥有的资源路径
        Admin admin = adminService.findAdminByUserName(username);
        if (admin == null) {
            return false;
        }
        if (admin.getId() == 1) { //1为超级管理员
            return true;
        }
        //查询资源路径集合
        //select path from ms_permission as m where m.id in (select ap.permission_id from ms_admin_permission as ap where ap.admin_id = 1)
        List<Permission> permissionList = adminService.findPermissionsByAdminId(admin.getId());
        requestURI = StringUtils.split(requestURI, '?')[0];
        for (Permission permission : permissionList) {
            if (requestURI.equals(permission)) {
                return true;
            }
        }
        return false;
    }
}
